﻿using ZquenceStudio3Host.Commands.BuiltInCommands;
using ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.GUI;

namespace ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.Commands
{
    class DisconnectOutputCommand : BaseCommand
    {
        private BaseModulizerUI mNodisizer;
        private ModulizerUIv2 mNodisizerV2;
        private ModuleOutput mOutput;
        private ModuleInput mInput;
        private bool mUserNotFirst;

        public override object[] ReferenceObjects
        {
            get { return RefereceObject(mInput); }
        }

        public DisconnectOutputCommand(BaseModulizerUI nodisizer, ModuleInput connectoToInput)
        {
            Init(connectoToInput);

            mNodisizer = nodisizer;
        }

        public DisconnectOutputCommand(ModulizerUIv2 nodisizer, ModuleInput connectoToInput)
        {
            Init(connectoToInput);

            mNodisizerV2 = nodisizer;
        }

        private void Init(ModuleInput connectoToInput)
        {
            if (connectoToInput == null)
            {
                throw new System.ArgumentNullException(nameof(connectoToInput));
            }
            if (connectoToInput.FromOutput == null)
            {
                throw new System.Exception("Can not disconnect input that is not connected.");
            }

            mInput = connectoToInput;
            mOutput = connectoToInput.FromOutput;
        }

        protected override void Execute()
        {
            mInput.FromOutput = null;

            // Flag. First time is always a user that connect. Do not go into parent.
            if (mUserNotFirst)
            {
                if (mNodisizerV2 != null)
                {
                    mNodisizerV2.GoInto(mOutput.Module.ParentModule, false);
                }
                else
                {
                    mNodisizer.RebuildSynthGraphModuleParent(mOutput.Module);
                }
            }
            mUserNotFirst = true;

            if (mNodisizerV2 != null)
            {
                mNodisizerV2.UpdateParameterStates();
            }
            else
            {
                mNodisizer.UpdateParameterStates();
            }
        }

        protected override void UnExecute()
        {
            mOutput.AddInput(mInput);

            if (mNodisizerV2 != null)
            {
                mNodisizerV2.GoInto(mOutput.Module.ParentModule, false);
                mNodisizerV2.UpdateParameterStates();
            }
            else
            {
                mNodisizer.RebuildSynthGraphModuleParent(mOutput.Module);
                mNodisizer.UpdateParameterStates();
            }
        }

        public override string ToString()
        {
            return "Disconnected input.";
        }
    }
}
